package com.styletransfer.service;

import com.styletransfer.exception.BusinessException;
import com.styletransfer.mapper.CombinationMapper;
import com.styletransfer.mapper.FavoriteMapper;
import com.styletransfer.mapper.StyleMapper;
import com.styletransfer.model.ApiResponse;
import com.styletransfer.model.Favorite;
import com.styletransfer.model.PageRequest;
import com.styletransfer.model.PageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 收藏服务类
 *
 * 这个类负责处理与收藏相关的业务逻辑，包括用户对风格和组合的收藏操作。
 */
@Service
public class FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private StyleMapper styleMapper;

    @Autowired
    private CombinationMapper combinationMapper;

    /**
     * 添加收藏
     *
     * @param favorite 收藏对象
     * @return API响应
     */
    @Transactional
    public ApiResponse<Favorite> addFavorite(Favorite favorite) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        favorite.setUserId(userId);

        // 检查收藏类型
        if (favorite.getType() == null) {
            throw new BusinessException("收藏类型不能为空");
        }

        // 检查收藏对象是否存在
        if (favorite.getType() == 1) { // 风格
            if (styleMapper.findById(favorite.getTargetId()) == null) {
                throw new BusinessException("风格不存在");
            }
        } else if (favorite.getType() == 2) { // 组合
            if (combinationMapper.findById(favorite.getTargetId()) == null) {
                throw new BusinessException("组合不存在");
            }
        } else {
            throw new BusinessException("收藏类型无效");
        }

        // 检查是否已收藏
        Favorite existingFavorite = favoriteMapper.findByUserAndTarget(userId, favorite.getTargetId(), favorite.getType());
        if (existingFavorite != null) {
            throw new BusinessException("已经收藏过了");
        }

        // 设置默认值
        favorite.setCreateTime(new Date());

        // 插入收藏
        favoriteMapper.insert(favorite);

        // 增加收藏数
        if (favorite.getType() == 1) { // 风格
            styleMapper.incrementFavoriteCount(favorite.getTargetId());
        } else if (favorite.getType() == 2) { // 组合
            combinationMapper.incrementFavoriteCount(favorite.getTargetId());
        }

        return ApiResponse.success(favorite);
    }

    /**
     * 取消收藏
     *
     * @param type 收藏类型（1:风格, 2:组合）
     * @param targetId 目标ID
     * @return API响应
     */
    @Transactional
    public ApiResponse<Void> cancelFavorite(Integer type, Long targetId) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 检查是否已收藏
        Favorite favorite = favoriteMapper.findByUserAndTarget(userId, targetId, type);
        if (favorite == null) {
            throw new BusinessException("未收藏过");
        }

        // 删除收藏
        favoriteMapper.delete(favorite.getId());

        // 减少收藏数
        if (type == 1) { // 风格
            styleMapper.decrementFavoriteCount(targetId);
        } else if (type == 2) { // 组合
            combinationMapper.decrementFavoriteCount(targetId);
        }

        return ApiResponse.success();
    }

    /**
     * 检查是否已收藏
     *
     * @param type 收藏类型（1:风格, 2:组合）
     * @param targetId 目标ID
     * @return API响应
     */
    public ApiResponse<Boolean> checkFavorite(Integer type, Long targetId) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 检查是否已收藏
        Favorite favorite = favoriteMapper.findByUserAndTarget(userId, targetId, type);

        return ApiResponse.success(favorite != null);
    }

    /**
     * 查询用户的收藏
     *
     * @param type 收藏类型（1:风格, 2:组合）
     * @return API响应
     */
    public ApiResponse<List<Favorite>> findByUser(Integer type) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 查询收藏
        List<Favorite> favorites = favoriteMapper.findByUser(userId, type);

        return ApiResponse.success(favorites);
    }

    /**
     * 分页查询用户的收藏
     *
     * @param type 收藏类型（1:风格, 2:组合）
     * @param pageRequest 分页请求
     * @return 分页响应
     */
    public PageResponse<Favorite> findByUserAndPage(Integer type, PageRequest pageRequest) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 计算偏移量
        Integer offset = (pageRequest.getPageNum() - 1) * pageRequest.getPageSize();

        // 查询数据
        List<Favorite> favorites = favoriteMapper.findByUserAndPage(userId, type, offset, pageRequest.getPageSize());
        Long total = favoriteMapper.countByUser(userId, type);

        // 构建分页响应
        return new PageResponse<>(favorites, total, pageRequest.getPageNum(), pageRequest.getPageSize());
    }

    /**
     * 获取当前用户ID
     *
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal = authentication.getPrincipal();

            // 从自定义UserDetails中获取用户ID
            if (principal instanceof com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) {
                return ((com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) principal).getUserId();
            }

            // 尝试从请求属性中获取用户ID
            javax.servlet.http.HttpServletRequest request =
                    ((org.springframework.web.context.request.ServletRequestAttributes)
                            org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest();
            Object userId = request.getAttribute("userId");
            if (userId != null) {
                return (Long) userId;
            }

            throw new RuntimeException("无法获取用户ID");
        } catch (Exception e) {
            throw new RuntimeException("获取用户ID失败: " + e.getMessage());
        }
    }
}
